<?php
	require_once('_inc.php');


	$db	=& D::$db;

	if( $_GET['act'] === 'save' ){
		$update	= json_decode($_POST['update']);
		if(is_array($update))  foreach($update as $row){
			$sql	= array();
			foreach($row as $k => $v){				
				if($k!='id'){
					$sql[]	= $k .' = ' .$db->quote($v);
				}
			}
			$sql	= "UPDATE units SET ". join(',', $sql)." WHERE id=" . ((int) $row->id );
			$db->query($sql);
		}
		$insert	= json_decode($_POST['insert']);
		if(is_array($insert))  foreach($insert as $row){
			$sql	= array();
			$sql2	= array();
			foreach($row as $k => $v){				
				if($k!='id'){
					$sql[]	= $db->quote($v);
					$sql2[]	= $k;
				}
			}
			$sql	= "INSERT INTO units ( ". join(',', $sql2).") VALUE ("
			.join(',', $sql).")\n";
			$db->query($sql);
		}
		$del	= json_decode($_POST['del']);
		if( !empty($del) ){
			$sql	= "DELETE FROM units WHERE id=".join(' or id=', $del);
			$db->query($sql);
		}
		update($db);
		die('ok');
	}

	if( $_GET['act'] === 'list' ){
		
		$L		= array();
		$L['root']	= $db->all("SELECT * FROM units WHERE 1");
		$L['Total']	= count($L['root']);
		echo json_encode($L);
		die;
	}


	D::$user->tpl()->display();

	function update(&$db){
		$path	= D::$user->path();
		$L	= array();
		$L['root']	= $db->all('SELECT id,单位,采食量单位 FROM units WHERE 1');
		file_put_contents($path.'/units.js', json_encode($L));
	}
?>